//
//  PersonalUserVideorViewController.m
//  ChatForHot
//
//  Created by wr on 2018/10/11.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "PersonalUserVideorViewController.h"
#import "PersonalUserPhotoVideoCell.h"
#import "XMPlayerView.h"
#import "PreviewUserPhotoViewController.h"
#import "UserVideoUploadViewController.h"
#import "HCAssetModel.h"
#import "EMCDDeviceManager.h"
#import "HCPhotoManager.h"

@interface PersonalUserVideorViewController ()        <UICollectionViewDataSource,UICollectionViewDelegate,UploadVideoSelectedDelegate,MWPhotoBrowserDelegate>

@property (nonatomic, assign) PhotoType photoType;
@property (nonatomic, strong) UICollectionView *HOTCHATVideoCollectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *uploadArray;
@property (nonatomic, assign) NSInteger selectedRow;
@property (nonatomic, strong) PreviewUserPhotoViewController *HOTCHATphotoBrowser;
@property (nonatomic, strong) UINavigationController *nv;
@property (nonatomic, strong) UIButton *HOTCHATupButton;
@property (nonatomic, strong) UIButton *HOTCHATdelButton;
@property (nonatomic, strong) UIButton *HOTCHATdelButton2;
@property (nonatomic, assign) BOOL isEditMode;
@property (nonatomic, assign) BOOL isUploading;
@property (nonatomic, assign) BOOL loadself;
@end

@implementation PersonalUserVideorViewController

- (instancetype)initWithPhotoType:(NSInteger)photoType {
    if (self = [super init]) {
        self.photoType = photoType;
        [self HOTCHATstartLoading];
        [self HOTCHATgetPhotos];
        if (self.photoType == PrivatePhoto) {
        } else {
        }
        self.selectedRow = -1;
    }
    return self;
}

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.HOTCHATphotoBrowser = [[PreviewUserPhotoViewController alloc] initWithDelegate:self];
    self.HOTCHATphotoBrowser.displayActionButton = NO;
    self.HOTCHATphotoBrowser.displayNavArrows = YES;
    self.HOTCHATphotoBrowser.displaySelectionButtons = NO;
    self.HOTCHATphotoBrowser.alwaysShowControls = NO;
    self.HOTCHATphotoBrowser.zoomPhotosToFill = YES;
    self.HOTCHATphotoBrowser.enableGrid = NO;
    self.HOTCHATphotoBrowser.startOnGrid = NO;
    self.HOTCHATphotoBrowser.isSelf = YES;
    [self.HOTCHATphotoBrowser setCurrentPhotoIndex:0];
    
    self.nv = [[UINavigationController alloc] initWithRootViewController:self.HOTCHATphotoBrowser];
    
    self.dataArray = [[NSMutableArray alloc] init];
    self.uploadArray = [[NSMutableArray alloc] init];
}

- (void)HOTCHATInsertSubViews {
    [super HOTCHATInsertSubViews];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.HOTCHATVideoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.HOTCHATVideoCollectionView.dataSource = self;
    self.HOTCHATVideoCollectionView.delegate = self;
    [self.HOTCHATVideoCollectionView registerClass:[PersonalUserPhotoVideoCell class] forCellWithReuseIdentifier:@"PersonalUserPhotoVideoCell"];
    self.HOTCHATVideoCollectionView.showsHorizontalScrollIndicator = NO;
    self.HOTCHATVideoCollectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.HOTCHATVideoCollectionView];
    
    self.HOTCHATupButton = [[UIButton alloc] init];
    [self.HOTCHATupButton setTitle:NSLocalizedString(@"userPhoto1", nil) forState:UIControlStateNormal];
    [self.HOTCHATupButton setTitle:NSLocalizedString(@"userPhoto1", nil) forState:UIControlStateHighlighted];
    [self.HOTCHATupButton addTarget:self action:@selector(HOTCHATuploadPhoto) forControlEvents:(UIControlEventTouchUpInside)];
    [self.HOTCHATupButton setBackgroundImage:[[UIImage imageNamed:@"personal_iden_sav_n"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateNormal)];
    [self.HOTCHATupButton setBackgroundImage:[[UIImage imageNamed:@"personal_iden_sav_h"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.HOTCHATupButton];
    
    self.HOTCHATdelButton = [[UIButton alloc] init];
    self.HOTCHATdelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.HOTCHATdelButton setTitle:NSLocalizedString(@"userPhoto2", nil) forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton addTarget:self action:@selector(HOTCHATdelAction) forControlEvents:(UIControlEventTouchUpInside)];
    UIColor *color = [UIColor colorFromHexString:@"F04D32"];
    [self.HOTCHATdelButton setTitleColor:color forState:UIControlStateNormal];
    [self.HOTCHATdelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [self.HOTCHATdelButton setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del_hig"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.HOTCHATdelButton];
    
    self.HOTCHATdelButton2 = [[UIButton alloc] init];
    self.HOTCHATdelButton2.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.HOTCHATdelButton2 setTitle:NSLocalizedString(@"userPhoto2", nil) forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton2 addTarget:self action:@selector(HOTCHATdelAction2) forControlEvents:(UIControlEventTouchUpInside)];
    [self.HOTCHATdelButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.HOTCHATdelButton2 setTitleColor:color forState:UIControlStateHighlighted];
    self.HOTCHATdelButton2.hidden = YES;
    [self.HOTCHATdelButton2 setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del_hig"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateNormal)];
    [self.HOTCHATdelButton2 setBackgroundImage:[[UIImage imageNamed:@"personal_btn_del"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20) resizingMode:(UIImageResizingModeStretch)] forState:(UIControlStateHighlighted)];
    [self.view addSubview:self.HOTCHATdelButton2];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.HOTCHATVideoCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(self.HOTCHATupButton.mas_top).offset(-10);
    }];
    
    [self.HOTCHATupButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 55);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-84);
        make.height.mas_equalTo(44);
    }];
    
    [self.HOTCHATdelButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.HOTCHATupButton);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(kScreenWidth - 55);
    }];
    
    [self.HOTCHATdelButton2 mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.HOTCHATdelButton);
    }];
}

#pragma mark UICollectionDatasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PersonalUserPhotoVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PersonalUserPhotoVideoCell" forIndexPath:indexPath];
    cell.isEditMode = self.isEditMode;
    cell.model = [self.dataArray objectAtIndex:indexPath.row];
    return cell;
}

#pragma mark UICollectionview Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isEditMode) {
        PersonalUserPhotoVideoCell *cell = (PersonalUserPhotoVideoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.model.isSelected = !cell.model.isSelected;
    }else{
        PersonalUserPhotoVideoCell *cell = (PersonalUserPhotoVideoCell *)[collectionView cellForItemAtIndexPath:indexPath];
        XMPlayerView *playerManager = [[XMPlayerView alloc] init];
        playerManager.sourceImagesContainerView = (UIView *)cell.HOTCHATphotoImageView;
        playerManager.currentImage = cell.HOTCHATphotoImageView.image;
        playerManager.videoURL = [NSURL URLWithString:[cell.model.videoAddress HOTCHATTotalStringUrl]];
        [playerManager show];
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger cellwidth = (CGRectGetWidth(collectionView.frame) - 10 * 4) / 3;
    return CGSizeMake(cellwidth, cellwidth);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark - photoDeleteAction
- (void)HOTCHATdelAction{
    self.isEditMode = YES;
    self.HOTCHATdelButton.hidden = YES;
    self.HOTCHATdelButton2.hidden = NO;
    [self.HOTCHATVideoCollectionView reloadData];
}
- (void)HOTCHATdelAction2{
    self.isEditMode = NO;
    self.HOTCHATdelButton.hidden = NO;
    self.HOTCHATdelButton2.hidden = YES;
    [self HOTCHATdeleteVideos];
    [self.HOTCHATVideoCollectionView reloadData];
}

- (void)HOTCHATuploadPhoto{
    UserVideoUploadViewController *pvc = [[UserVideoUploadViewController alloc] init];
    pvc.isVideo = YES;
    pvc.maxCount = 20 - self.dataArray.count;
    pvc.delegate = self;
    [self.navigationController pushViewController:pvc animated:YES];
}

- (void)HOTCHATselectedVideoArray:(NSArray *)array{
    if (array.count > 0) {
        self.loadself = YES;
        [self.uploadArray addObjectsFromArray:array];
    }else{
        return;
    }
    [self HOTCHATstartLoading];
    [self HOTCHATstartUpload];
}
- (void)HOTCHATstartUpload{
    if (self.isUploading) {
        return;
    }
    if (self.uploadArray.count > 0) {
        [self HOTCHATuploadPhotoWithObj:[self.uploadArray firstObject]];
    }else{
        if (self.loadself) {
            [self HOTCHATgetPhotos];
        }else{
            [self HOTCHATstopLoading];
        }
    }
}
- (void)HOTCHATuploadPhotoWithObj:(id)obj{
    NSURL *vdURL;
    if ([obj isKindOfClass:[NSURL class]]) {
        vdURL = obj;
        NSInteger times = [[HCPhotoManager shareManager] HOTCHATgetAudioTimesWithURL:vdURL];
        [self upWithVideoDatas:vdURL times:times];
    }else if ([obj isKindOfClass:[HCAssetModel class]]){
        HCAssetModel *model = obj;
        PHAsset *phasset = model.asset;
        [self fetchDataFromAsset:model.asset vd:^(NSURL *vdl) {
            [self upWithVideoDatas:vdl times:phasset.duration];
        }];
        return;
    }else{
        [self HOTCHATstopLoading];
        return;
    }
}

- (void)upWithVideoDatas:(NSURL *)videoURL times:(NSInteger)timess{
    @weakify(self)
    if (videoURL.absoluteString.length > 0) {
        self.isUploading = YES;
        NSMutableDictionary *mparameters = [[NSMutableDictionary alloc] init];
        [mparameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
        [mparameters setValue:[NSNumber numberWithInteger:self.photoType + 2] forKey:@"type"];
        [mparameters setValue:@(timess) forKey:@"time"];
        
        [NetWorkTool HOTCHATUploadImageData:UerPhotoUploadVideo_URL parameters:mparameters fileData:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSError *error;
            [formData appendPartWithFileURL:videoURL name:@"uploadfile" error:&error];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            NSLog(@"%@",uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSString * _Nonnull HOTCHATmsgCode, NSDictionary * _Nonnull HOTCHATresultDic) {
            @strongify(self)
            self.isUploading = NO;
            NSString *code = [HOTCHATresultDic valueForKey:@"code"];
            if ([code isEqualToString:@"0"]) {
                [NetWorkTool HOTCHATUpdateToken];
                [self HOTCHATgetPhotos];
                [self HOTCHATupNextPhoto];
            }else{
                [self HOTCHATstopLoading];
            }
            
            if ([code isEqualToString:@"1"]) {
                NSString *message = [HOTCHATresultDic valueForKey:@"message"];
                if (message.length > 0) {
                    [NetWorkTool HOTCHATshowMessage:message];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSError * _Nonnull error) {
            @strongify(self)
            self.isUploading = NO;
            NSLog(@"%@",error);
            [self HOTCHATstopLoading];
        }];
    }else{
        [self HOTCHATupNextPhoto];
    }
}

- (void)HOTCHATupNextPhoto{
    if (self.uploadArray.count > 0) {
        [self.uploadArray removeObjectAtIndex:0];
    }
    [self HOTCHATstartUpload];
}

- (void)fetchDataFromAsset:(PHAsset *)phAsset vd:(void (^)(NSURL *vd))vdBlock{
    if (phAsset.mediaType == PHAssetMediaTypeVideo) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            
            NSURL *url = urlAsset.URL;
            NSURL *mp4url = [self _convert2Mp4:url];
            if (mp4url) {
                vdBlock(mp4url);
            }else {
                vdBlock(url);
            }
        }];
    }else{
        vdBlock(nil);
    }
}

- (NSURL *)_convert2Mp4:(NSURL *)movUrl
{
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetMediumQuality];
        NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", [EMCDDeviceManager dataPath], (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
        mp4Url = [NSURL fileURLWithPath:mp4Path];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            wait = nil;
        }
    }
    return mp4Url;
}

#pragma mark - requestVideoList

- (void)HOTCHATgetPhotos{
    @weakify(self)
    NSMutableDictionary *mparameters = [[NSMutableDictionary alloc] init];
    [mparameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
    [mparameters setValue:[NSNumber numberWithInteger:self.photoType + 2] forKey:@"type"];
    
    [NetWorkTool HOTCHATRequestWithStringURL:GetUerPhotoPic_URL progress:^(NSProgress * _Nonnull progress) {
    } RequestWay:@"GET" Parma:mparameters SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        @strongify(self)
        if (self.uploadArray.count == 0) {
            [self HOTCHATstopLoading];
        }
        if (isSucess) {
            NSArray *keyDic = [resultDictionary valueForKey:@"data"];
            if (keyDic.count > 0) {
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:[PersonalUserPhotoModel HOTCHATgetArrayFromDic:resultDictionary]];
                [self.HOTCHATVideoCollectionView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                [self.HOTCHATVideoCollectionView hideEmptyView];
            }else {
                [self.HOTCHATVideoCollectionView showEmptyViewWithImage:[UIImage imageNamed:@"p_album_ic_no"]];
            }
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        @strongify(self)
        [self HOTCHATstopLoading];
    }];
}

#pragma mark - PreviewAction
- (void)HOTCHATpreviewPhotoWithIndex:(NSInteger)index{
    [self.HOTCHATphotoBrowser reloadData];
    [self.HOTCHATphotoBrowser setCurrentPhotoIndex:index];
    [self presentViewController:self.nv animated:YES completion:^{
        
    }];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    return self.dataArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    PersonalUserPhotoModel *model = [self.dataArray objectAtIndex:index];
    return [MWPhoto photoWithURL:[NSURL URLWithString:[model.picAddress HOTCHATTotalStringUrl]]];
}

- (void)deletePhotoAtIndex:(NSInteger)index{
    UIAlertController *asheet = [UIAlertController alertControllerWithTitle:nil message:@"Delete the photo?" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancelaction = [UIAlertAction actionWithTitle:NSLocalizedString(@"", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okaction = [UIAlertAction actionWithTitle:NSLocalizedString(@"", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if (index >= 0 && index < self.dataArray.count) {
            PersonalUserPhotoModel *model = [self.dataArray objectAtIndex:index];
            [self HOTCHATdeletePhotoByID:model.photoid];
            [self.dataArray removeObjectAtIndex:index];
            [self.HOTCHATVideoCollectionView reloadData];
            [self.HOTCHATphotoBrowser reloadData];
        }
    }];
    
    [asheet addAction:cancelaction];
    [asheet addAction:okaction];
    
    [self.nv presentViewController:asheet animated:YES completion:^{
    }];
}

- (void)HOTCHATdeletePhotoByID:(NSString *)photoID{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:photoID forKey:@"photoid"];
    [NetWorkTool HOTCHATRequestWithStringURL:GetUerPhotoDeletePic_URL progress:^(NSProgress * _Nonnull progress) {
    } RequestWay:@"POST" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        if (isSucess) {
            [NetWorkTool HOTCHATshowMessage:NSLocalizedString(@"userPhoto7", nil)];
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)HOTCHATdeleteVideos{
    for (NSInteger i = self.dataArray.count - 1; i >= 0; i --) {
        PersonalUserPhotoModel *model = self.dataArray[i];
        if (model.isSelected) {
            [self HOTCHATdeletePhotoByID:model.photoid];
            [self.dataArray removeObjectAtIndex:i];
        }
    }
}

@end
